<?php


namespace App\Service\Client;


use App\Constants\ContextKey;
use App\Constants\DefaultValue;
use App\Constants\ErrorCode;
use App\Dao\UserDao;
use App\Exception\BusinessException;
use App\Model\Cooperative;
use App\Model\User;
use App\Utils\Log;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Request;
use Hyperf\Utils\Context;
use Monolog\Handler\IFTTTHandler;

class BaseService
{
    /**
     * @Inject()
     * @var UserDao
     */
    protected $userDao;

    /**
     * 用户信息
     * @return User
     */
    protected function userInfo(): User
    {
        return Context::get(ContextKey::USER);
    }

    /**
     * 运营商信息
     * @return Cooperative
     */
    protected function cooperativeInfo(): Cooperative
    {
        return Context::get(ContextKey::COOPERATIVE);
    }

    /**
     * document_root路径
     * @return mixed|string
     */
    protected function documentRoot()
    {
        return config('server.settings.document_root');
    }

    /**
     * 迁移文件
     * @param $oldFilePath
     * @param $newFileDir
     * @return string
     */
    protected function moveTmpFile($oldFilePath, $newFileDir)
    {
        try {
            //如果不是临时文件，则不迁移
            if (substr($oldFilePath, 0, 5) != '/tmp/') {
                return $oldFilePath;
            }

            $oldFilePathReal = $this->documentRoot() . $oldFilePath;
            $newFileDirReal = $this->documentRoot() . $newFileDir;

            if (!is_dir($newFileDirReal)) {
                mkdir($newFileDirReal, 0777, true);
            }

            $oldFileInfo = pathinfo($oldFilePathReal);
            $oldFileName = $oldFileInfo['basename'];

            $newFilePathReal = $newFileDirReal . '/' . $oldFileName;
            copy($oldFilePathReal, $newFilePathReal);

            return $newFileDir . '/' . $oldFileName;
        } catch (\Throwable $e) {
            Log::get()->error($e->getCode(), [$e->getMessage(), $oldFilePath, $newFileDir]);
            Log::get()->error($e->getTraceAsString());
            throw new BusinessException(ErrorCode::FILE_MOVE_FAIL);
        }
    }

    /**
     * 删除文件（document_root路径）
     * @param $filePath
     */
    protected function deleteFile($filePath)
    {
        if ($filePath != '') {
            $filePathReal = $this->documentRoot() . $filePath;
            if (file_exists($filePathReal)) {
                unlink($filePathReal);
            }
        }
    }

    /**
     * 图片后缀
     * @return array|string[]
     */
    protected function imageSuffix(): array
    {
        return [
            'jpg',
            'jpeg',
            'gif',
            'wbmp',
            'png'
        ];
    }

    /**
     * 图片mime类型
     * @return array|string[]
     */
    protected function imageMime(): array
    {
        return [
            'image/jpg',
            'image/jpeg',
            'image/gif',
            'image/wbmp',
            'image/png'
        ];
    }

    /**
     * 时间随机数
     * @return string
     */
    protected function timeRandom()
    {
        list($usec, $sec) = explode(" ", microtime());
        mt_srand();
        $random = mt_rand(100000, 999999);
        $usec = $usec * 1000000;
        return "{$sec}{$usec}{$random}";
    }

    /**
     * 随机字符串
     * @param int $length
     * @return false|string
     */
    protected function randString(int $length = 6)
    {
        $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
        $randStr = str_shuffle($str);
        return substr($randStr, 0, $length);
    }


    /**
     * 任务单价转金币
     * @param $price
     * @return string
     */
    protected function price2gold($price)
    {
        return bcmul((string)$price, (string)DefaultValue::GOLD_PERCENT);
    }

    /**
     * 当前用户在所有平台的悬赏主id
     * @return array
     */
    protected function userIdsInCooperatives(){
        $request = di(Request::class);
        $cooperative_id = $request->getHeaderLine('cooperative_id');

        $employerIds = [$this->userInfo()->id];

        if ($cooperative_id && $cooperative_id != '') {
            if ($cooperative_id == '-1') {
                $whereUser = [
                    'phone' => $this->userInfo()->phone,
                ];
            } else {
                $whereUser = [
                    'cooperative_id' => $cooperative_id,
                    'phone' => $this->userInfo()->phone
                ];
            }
            $users = $this->userDao->select($whereUser);
            if (!$users) {
                throw new BusinessException(ErrorCode::USER_NOT_EXIST);
            }

            $usersArray = $users->toArray();
            $employerIds = array_column($usersArray, 'id');
        }

        return $employerIds;
    }
}